<template>
  <div
    class="scan-input-box"
    :class="disabled ? 'scan-input-box-disabeld' : ''"
  >
    <el-input
      ref="codeInput"
      v-model="code"
      :clearable="true"
      style="width: 400px"
      :disabled="disabled"
      placeholder="请扫码或输入资产卡片号"
      @keyup.enter.native="sacn"
      @input="(e) => (code = validSe(e))"
    >
      <template #prepend>资产卡片号</template>
    </el-input>
  </div>
</template>

<script setup name="ScanInputBox">
import { assetCardScan } from '@/api/core.js'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  query: {
    type: Object,
    default: undefined,
  },
  api: {
    type: Function,
    default: assetCardScan,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

const code = ref('')

function sacn() {
  if (!code.value) {
    proxy.$message({
      message: '请扫描资产编码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let param = {
    assetCode: proxy.$fn.setTrim(code.value),
    ...props.query,
  }
  console.log(param)
  props
    .api(param)
    .then((res) => {
      if (res && res.success) {
        scanResult(res.data)
      }
      code.value = ''
    })
    .catch(() => {
      code.value = ''
    })
}

function scanResult(detail) {
  if (detail && detail.id) {
    let data = detail
    if (data.isLocked && data.isLocked === 1) {
      proxy.$message({
        message: `资产${data.assetName}${data.lockedReason}`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    data.isChoice = true
    emits('callback', data, (val) => {
      if (val) {
        proxy.$message({
          message: `该资产已在列表中或重复扫码`,
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
      } else {
        proxy.$message({
          message: `扫码成功`,
          type: 'success',
          duration: 3500,
          showClose: true,
        })
      }
    })
  } else {
    proxy.$message({
      message: `找不到当前扫码对应资产！`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
}
</script>

<style scoped></style>
